#include "MEpoll.h"

MEpoll::MEpoll(int maxNum)
{
    initOk = false;
    this->maxNum = maxNum;
    fd = epoll_create(maxNum);
	if(fd == -1)
    {
		printf("epoll_create error!\r\n");
        return;
	}

    events = new epoll_event[maxNum];
    if(!events)
    {
        printf("new epoll_event error!\r\n");
        return;
    }

    initOk = true;
}

int MEpoll::Add(int fd, unsigned int param)
{
    int ret = 0;
    struct epoll_event ev;
    ev.events = param;
    ev.data.fd = fd;

    if(initOk)
    {
        ret = epoll_ctl(this->fd, EPOLL_CTL_ADD, ev.data.fd, &ev);
    }
    else
    {
        ret = -1;
        printf("init failed\r\n");
    }

    return ret;
}

int MEpoll::Wait(int timeout)
{
    int nfds = 0;

    if(initOk)
    {
        nfds = epoll_wait(this->fd, events, this->maxNum, timeout);
    }
    else
    {
        nfds = -1;
        printf("init failed\r\n");
        sleep(1);
    }

    return nfds;
}

struct epoll_event * MEpoll::GetEvents(void)
{
    return events;
}
